#include using namespace std; void modprintarr(char *, int [], int); void printarr(char *, int [], int); void swapval(int a, int b); void swapptr(int *a, int *b); void swapref(int &a, int &b); void main(){ /* This is not a solution for variable sized arrays. It will not compile. int x; cout << "enter size of array" << endl; cin >> x; int a[x];// will not compile */ int a[10]; // what does this print? cout << a << endl; // a is the address of the start of the array! // proof cout << &a[0] << endl; // set up a pointer to the array int *p = a; for(int i=0; i<10; i++) p[i]=i; modprintarr(" after initializing p ",p,10); modprintarr(" after call to modifying print ",p,10); int *move = a; cout << move << endl; cout << ++move << endl; cout << &a[1] << endl;// prove move and &a[1] same int count = 50; for(move = a; move < a + 10; move++) *move = count--; //printarr("after using moving pointer",move,10); move beyond a printarr("after using moving pointer",a,10); // now show dynamic memory allocation of an array cout << "enter the size of the array" << endl; int x; cin >> x; p = new int[x]; if(p != 0){ for(int i = 0; i < x; i++) p[i] = i*i; printarr(" i squared using dynamic allocation",p,x); delete [] p; } else{ cout << "allocation failed" << endl; } int xray = 555, zebra = -2; cout << "original " << endl; cout << xray << " " << zebra << endl; swapval(xray, zebra); cout << "after swapval " << endl; cout << xray << " " << zebra << endl; swapptr(&xray, &zebra); cout << "after swapptr " << endl; cout << xray << " " << zebra << endl; swapref(xray, zebra); cout << "after swapref " << endl; cout << xray << " " << zebra << endl; } void modprintarr(char *msg, int a[], int size){ cout << msg << endl; for(int i = 0; i < size; i++) cout << a[i] << endl; a[3]=7777;//prove pass by reference } void printarr(char *msg, int a[], int size){ cout << msg << endl; for(int *p = a; p < a + size; p++) cout << *p << endl; } // only swaps local copy void swapval(int a, int b){ int t = a; a = b; b = t; } // actually swaps using the address of the variable void swapptr(int *a, int *b){ int t = *a; *a = *b; *b = t; } // actually swaps by renaming the variable void swapref(int &a, int &b){ int t = a; a = b; b = t; }